<?php

namespace apps\app\listeners;
if( ! APP_ROOT  )
    return 'Direct Access Deny!';

use \Phalcon\Events\Event;
use \Phalcon\Mvc\Dispatcher;
use \Phalcon\Mvc\User\Plugin;

class DispatcherListener extends Plugin
{
	// protected $_module;
	
	// public function __construct($module)
	// {
	// $this->_module = $module;
	// }
		
	
	public function beforeDispatch( Event $event, Dispatcher $dispatcher )
	{
		// echo $resource = $this->_module . '-' . $dispatcher->getControllerName(), PHP_EOL; // frontend-dashboard
		// echo $access = $dispatcher->getActionName(); // null
	}

	public function beforeException( Event $event, Dispatcher $dispatcher )
	{
		if( isset( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) )
		{ // ajax request
			return;
		}
		
		// if( $SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' );
		// strtolower(
		
		$dispatcher->forward( array(
				'module' => 'app',
				'controller' => 'error',
				'action' => 'err404' 
		) );
		
		return false;
	}

	/**
	 * @author( author='zlw' )
	 * @date( date = '2015-9-6' )
	 * @comment( comment = '前台日志（用户访问日志，用户操作日志）,session安全' )	
	 * @method( method = 'beforeDispatchLoop' )
	 * @op( op = '' )		
	*/
	public function beforeDispatchLoop( Event $event, Dispatcher $dispatcher )
	{
		$keyParams = array();
		$params = $dispatcher->getParams();
		
		foreach( $params as $k => $v )
		{
			if( $k & 1 )
			{
				$keyParams[ $params[ $k - 1 ]] = $v;
			}
		}
		
		$dispatcher->setParams( $keyParams );
		
		/**
		//前端 session 安全管理 ( 浏览器 + ip地址 )
		$memInfo = $this->session->get( 'memInfo' );
		if( $memInfo )
		{
			
			$strVerfiy =  trim( $_SERVER[ 'HTTP_USER_AGENT' ] ) . trim( $_SERVER[ 'REMOTE_ADDR' ] );
			if( $memInfo[ 'session_verfiy' ] != $strVerfiy  )
			{
				$this->queue->put( array(
						'type' => \enums\LogEnums::LOG_MEM_SESSION_LOG,
						'body' => array(
								'userId' => $memInfo['mem_id'],
								'userName' => $memInfo['login'],
								'addTime' => $_SERVER['REQUEST_TIME'],
								'url' 	=> $_SERVER['REQUEST_URI']
						)
				));
				return;
			}
				
				
			$homeRegTime = $this->config[ 'home_regenarater_time_interval' ];
			$currTime = intval( $_SERVER[ 'REQUEST_TIME' ] - $memInfo[ 'home_regenarater_time' ] );
			if( $currTime > $homeRegTime )
			{
				//重新生成sessionid
				session_regenerate_id();
					
				$strVerfiy = trim( $_SERVER[ 'HTTP_USER_AGENT' ] ) . trim( $_SERVER[ 'REMOTE_ADDR' ] );
				$memInfo[ 'home_regenarater_time' ]	= $_SERVER[ 'REQUEST_TIME' ];
				$memInfo[ 'session_verfiy' ]  			= $strVerfiy;
				$this->session->set( 'memInfo', $memInfo );
			}
		}
		
		return false;
		
		//记录前台操作日志
		$method = strtolower( $dispatcher->getActionName() ) . 'action';
		$controller = strtolower( $dispatcher->getControllerName() ) . 'controller';
		
		$annotation = $this->memCache->get( 'mem_' . $controller . '_' . $method . '_cache' );
		if( !$annotation )
		{
			//注释信息读取失败 发送消息记录该异常消息 
			$this->queue->put( array(
					'type' => \enums\LogEnums::LOG_RECORDEXCEPTION,
					'body' => array(
							'message' => 'Error:[' . date("Y-m-d H:i:s",time()) . ']apps/home/' 
								. $controller.'/'. $method . '注释信息读取出错'
					)
			));
			return;
		}
		
		//cud操作记录于用户操作日志 ; r操作记录于用户访问日志; 其他则忽略
		$op = $annotation['op'];
		if( 'r' == $op )
		{
			$requestUri = strtolower( $_SERVER['REQUEST_URI'] );
			$isIndex = $requestUri === '/';
			$goodId  = strpos( $requestUri, 'goods/index/id') && $keyParams['id'] ? $keyParams['id'] : '';
			
			//判断biztype
			if( true == strpos( $requestUri, 'goods/index/id') && false != $goodId )
				$biztype = BizEnums::BIZ_DETAIL;
			else if( strpos( $requestUri, 'goods/search') )
				$biztype = BizEnums::BIZ_LIST;
			else if( true == $isIndex || ( 'goods' == strtolower( $dispatcher->getControllerName() ) && false == $goodId ) || 'index' == strtolower( $dispatcher->getControllerName() ) )
				$biztype = BizEnums::BIZ_HOME;
			else if( 'ads' == strtolower( $dispatcher->getControllerName() )  )
				$biztype = BizEnums::BIZ_ADS;
			else if( 'article' == strtolower( $dispatcher->getControllerName() ) )
				$biztype = BizEnums::BIZ_ARTICLE;
		
			if( $isIndex || $goodId || strpos( $requestUri, 'goods/search') )
			{
				$memInfo = $this->session->get( 'memInfo' );
				$this->queue->put( array(
						'type' => \enums\LogEnums::LOG_HOME_VISIT_LOG,
						'body' => array(
								'memId' => isset( $memInfo['mem_id'] ) ? $memInfo['mem_id'] : '',
								'ip' => $_SERVER['REMOTE_ADDR'],
								'addTime' => $_SERVER['REQUEST_TIME'],
								'agent' => $_SERVER['HTTP_USER_AGENT'],
								'goodId' => $goodId,
								'biztype'=> $biztype,
								'url' => APP_ROOT . 'apps' . ($isIndex ? '/home/index/index' : $requestUri),
								'refer' => isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : ''
						)
				) );
			}
		}
		elseif( '' == $op )
		{
			return;
		}
		elseif( 'c' == $op || 'u' == $op || 'd' == $op )
		{
			$memInfo = $this->session->get( 'memInfo' );
			//若无session信息且非注册操作，则返回
			if( !$memInfo && 'saveRegisterAction' != $method )
			{
				$this->queue->put( array(
						'type' => \enums\LogEnums::LOG_RECORDEXCEPTION,
						'body' => array(
								'message' => 'Error:[' . date("Y-m-d H:i:s",time()) . ']apps/home/'
								. $controller.'/'. $method . '访问用户session信息出错'
						)
				));
				return;
			}
			
			$this->queue->put( array(
					'type' => \enums\LogEnums::LOG_HOME_OPERATION_LOG,
					'body' => array(
							'userId' => $memInfo['mem_id'],
							'userName' => $memInfo['login'],
							'controller' => $controller,
							'action' => $method,
							'operation' => $op,
							'addTime' => $_SERVER['REQUEST_TIME'],
							'postContent' => $_POST,
							'url' => APP_ROOT . 'apps/' . $_SERVER['REQUEST_URI'] . 'Action'
					)
			));
		}
		else
		{
			//注释信息op字段存在非法字符
			$this->queue->put( array(
					'type' => \enums\LogEnums::LOG_RECORDEXCEPTION,
					'body' => array(
							'message' => 'Error:[' . date("Y-m-d H:i:s",time()) . ']apps/home/'
							. $controller.'/'. $method . '注释信息op字段存在非法字符'
					)
			));
			return;
		}
		*/
	}
}











